#include <fstream>
#include "json/json.h"

#include "Exceptions.h"
#include "Saving.h"

#include "Serialization.h"

namespace data
{
	void SetFileContents( std::string filename, std::string contents )
	{
		std::string text;
		std::ofstream file(filename.c_str());
		if(!file.is_open())
			throw ResourceOpenException( filename );

		file << contents;
		file.close();
	}

	void Save( std::string filename, const Json::Value& json )
	{
		Json::StyledWriter writer;
		std::string document = writer.write( json );
		SetFileContents( filename, document );
	}

	void SaveScene( const Scene* scene, std::string filename )
	{
		Json::Value jScene = SerializeScene( scene );
        Save( filename, jScene );
	}

	void SaveMap( const Map* map, std::string filename )
	{
		Json::Value jMap = SerializeMap( map );
        Save( filename, jMap );
	}

	void SaveObstacle( const Obstacle* obstacle, std::string filename )
	{
		Json::Value jObstacle = SerializeObstacle( obstacle );
        Save( filename, jObstacle );
	}

	void SaveCreatureDef( const CreatureDef* creatureDef, std::string filename )
	{
		Json::Value jCreatureDef = SerializeCreatureDef( creatureDef );
        Save( filename, jCreatureDef );
	}

	void SaveDetailDef( const DetailDef* detailDef, std::string filename )
	{
		Json::Value jDetailDef = SerializeDetailDef( detailDef );
        Save( filename, jDetailDef );
	}

	void SaveRotorDef( const RotorDef* rotorDef, std::string filename )
	{
		Json::Value jRotorDef = SerializeRotorDef( rotorDef );
        Save( filename, jRotorDef );
	}
}
